from tools.my_sql import MyMySQL
from settings import sql_settings
from tools.global_data import GlobalData
from tools.handle_replace_mark_data import replace_mark_data_by_re
from loguru import logger
import allure

@allure.step("===执行前置SQL语句===")
def excute_pre_sql(pre_sql_str):
    """
    处理pre_sql，执行sql语句，将查询结果设置为全局变量，全局变量key为pre_sql的key
    :param pre_sql_str: excel中pre_sql的数据，字符串
    :return:None
    """

    # 1.替换pre_sql中的占位符
    pre_sql_replace_str = replace_mark_data_by_re(pre_sql_str)
    # 转为字典格式
    pre_sql_replace_dict = eval(pre_sql_replace_str)

    # 2.数据库连接
    mysql = MyMySQL(**sql_settings)
    for key, sql in pre_sql_replace_dict.items():
        # 数据库查询结果为列表
        result_dict = mysql.get_result_from_database(sql)
        # 3.将mobile_code设置为全局变量
        if key != " " and result_dict is not None:
            logger.info("数据库查询结果result_dict:", result_dict)
            setattr(GlobalData, key, result_dict.get(key))
    mysql.close()


if __name__ == '__main__':
    setattr(GlobalData, "new_phone", "123456")
    excute_pre_sql(
        """{"mobile_code": 'SELECT mobile_code FROM tz_sms_log WHERE user_phone="#new_phone#" ORDER BY rec_date DESC LIMIT 1'}""")
    print(GlobalData.__dict__)
